home *** CD-ROM | disk | FTP | other *** search
- Path: newsroom.hitc.com!usenet
- From: psand@eos.hitc.com (G. Patrick Sand)
- Newsgroups: comp.lang.c++
- Subject: Re: Returning ref to object - is this code invalid?
- Date: 19 Jan 1996 19:06:20 GMT
- Organization: Hughes Aircraft (EOSDIS)
- Message-ID: <4doq3c$507@newsroom.hitc.com>
- References: <30F937D8.12D2@sierra.net>
- NNTP-Posting-Host: 155.157.118.56
- Mime-Version: 1.0
- X-Newsreader: WinVN 0.99.3
-
- In article <30F937D8.12D2@sierra.net>, snowbull@sierra.net says...
- >
- >Does the following code create a dangling reference?
- >
- >class vector
- >{ private: float x,y,z;
- > public: //c'tors & functions
- >};
- >
- >class face
- >{ private: vector v1, v2, v3;
- > public:
- > vector& get_vtx_1() const;
- >}
- >
- >vector& face::get_vtx_1() const //returns reference to vector
- >{ return v1;
- >}
- >
- >void main()
- >{
- > face ff('constructor parameters);
- > vector vv = ff.get_vtx_1();
- >}
- >
- >I'm wondering if the return of a reference to v1 will invalidate
- >my program since v1 goes out of scope when get_vtx_1() returns,
- >or does v1 stay in scope since ff is not deleted?
- >
- >Any input is appreciated!
- >
- >-TC
-
- It should stay in scope until the particular face instance (ff) is
- destroyed, since the vector members are assumed constructed either before
- (if they are arguments to the face constructors) or while face is being
- constructed... Here, the scope is based on class existence, not file or
- module scope. It is like the new and delete operators: until you kill
- (sorry, delete) it will hang around...
-
-
- The killer is when you create an object within a METHOD (not the class
- constructors) and try to return it by reference or pointer...you then
- have violated scope rules and are probably peeking into the program stack
- for wisdom and things to do...
-
- If your method did this:
-
- ...yada, yada, yada...
- {
- vector vtemp(v1);
- return &v1;
- }
-
- You are in hose-city with no way out...(give your PC the 3-fingered
- salute)
-
- Hope this helps....
-
- --
- G. Patrick Sand
- psand@eos.hitc.com
- PatSand@aol.com
- (301) 925-0791
- "Travel Light But Right..."
- Microsoft Network is prohibited from redistributing
- this work in any form, in whole or in part. License
- to distribute this individual post is available to Microsoft
- for $999. Posting without permission constitutes an
- agreement to these terms...gps
-
-